package mine.code.question.贪心;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

/**
 * 机器人在一个无限大小的网格上行走，从点(0, 0) 处开始出发，面向北方。该机器人可以接收以下三种类型的命令：
 * <p>
 * -2：向左转90 度
 * -1：向右转 90 度
 * 1 <= x <= 9：向前移动x个单位长度
 * 在网格上有一些格子被视为障碍物。
 * <p>
 * 第 i个障碍物位于网格点 (obstacles[i][0], obstacles[i][1])
 * <p>
 * 如果机器人试图走到障碍物上方，那么它将停留在障碍物的前一个网格方块上，但仍然可以继续该路线的其余部分。
 * <p>
 * 返回从原点到机器人的最大欧式距离的平方。
 *
 * @author caijinnan
 * @date 2019/12/24 11:33
 */
public class 模拟行走机器人 {

    @Test
    public void run() {
        int[] commands = {7, -2, -2, 7, 5};
        int[][] obstacles = {{-3, 2}, {-2, 1}, {0, 1}, {-2, 4}, {-1, 0}, {-2, -3}, {0, -3}, {4, 4}, {-3, 3}, {2, 2}};
        System.out.println(robotSim(commands, obstacles));
    }

    public int robotSim(int[] commands, int[][] obstacles) {
        int x = 0;
        int y = 0;
        int max = 0;
        int[] xForwardArr = {0, -1, 0, 1};
        int[] yForwardArr = {1, 0, -1, 0};
        int forwardIndex = 0;
        for (int command : commands) {
            if (command == -2) {
                forwardIndex = forwardIndex + 1;
                if (forwardIndex > 3) {
                    forwardIndex = 0;
                }
                continue;
            } else if (command == -1) {
                forwardIndex = forwardIndex - 1;
                if (forwardIndex < 0) {
                    forwardIndex = 3;
                }
                continue;
            }
            int xMove = command * xForwardArr[forwardIndex];
            int yMove = command * yForwardArr[forwardIndex];
            if (xMove != 0) {
                Set<Integer> set = new HashSet<>();
                for (int[] obstacle : obstacles) {
                    if (obstacle[1] == y) {
                        set.add(obstacle[0]);
                    }
                }
                for (int i = 0; i < Math.abs(xMove); i++) {
                    int temp = x + xForwardArr[forwardIndex];
                    if (set.contains(temp)) {
                        break;
                    }
                    x = temp;
                }
            } else if (yMove != 0) {
                Set<Integer> set = new HashSet<>();
                for (int[] obstacle : obstacles) {
                    if (obstacle[0] == x) {
                        set.add(obstacle[1]);
                    }
                }
                for (int i = 0; i < Math.abs(yMove); i++) {
                    int temp = y + yForwardArr[forwardIndex];
                    if (set.contains(temp)) {
                        break;
                    }
                    y = temp;
                }
            }
            max = Math.max(max, x * x + y * y);
        }
        return max;
    }


}
